﻿using Microsoft.AspNetCore.Mvc;
using Pay.DTO;
using Pay.Tool;
using System.ComponentModel.DataAnnotations;

namespace Pay.Controllers
{
	/// <summary>
	/// 框架接口
	/// </summary>
	[Route("api/[controller]")]
	[ApiController, ApiExplorerSettings(IgnoreApi = true)]
	public class FrameController : ControllerBase
	{
		private static object _lockObj = new object();
		/// <summary>
		/// ctor
		/// </summary>
		public FrameController()
		{
		}

		/// <summary>
		/// 获取框架数据
		/// </summary>
		[HttpGet("get.frame.config")]
		public async Task<string> GetFrameConfigAsync()
		{
			return await Task.FromResult(ToolHelper.GetFrameConfigJson());
		}

		/// <summary>
		/// 菜单列表
		/// </summary>
		[HttpGet("list.menu")]
		public async Task<List<MenuDto>> GetMenuListAsync()
		{
			return await Task.FromResult(Data.MenuData);
		}

		/// <summary>
		/// 获取支付配置列表
		/// </summary>
		[HttpPost("list.pay.config")]
		public async Task<LayuiResultDto<List<PayConfigDto>>> GetPayConfigListAsync()
		{
			var list = Data.PayConfigDic.Values.ToList();
			return await Task.FromResult(LayuiResultDto<List<PayConfigDto>>.Success(list, list.Count));
		}

		/// <summary>
		/// 增加支付配置
		/// </summary>
		[HttpPost("add.pay.config")]
		public async Task<BaseResultDto> AddPayConfig(PayConfigAddDto model)
		{
			if (Data.PayConfigDic.ContainsKey(model.PayCategory))
				return await Task.FromResult(BaseResultDto.Fail("同一支付类型只能一个配置"));
			lock(_lockObj )
			{
				var data = new PayConfigDto
				{
					AppId = model.AppId,
					ServerIp = model.ServerIp,
					WechatPayVersion = model.WechatPayVersion,
					PayCategory = model.PayCategory,
					WeChatPayOption = model.WeChatPayOption,
					AlipayOption = model.AlipayOption
				};
				if (data.AlipayOption != null)
                    data.AlipayOption.AppId = null;
				if (data.WeChatPayOption != null)
                    data.WeChatPayOption.AppId = null;
                Data.PayConfigDic.Add(data.PayCategory, data);
                ToolHelper.SaveJsonToFile(ToolHelper.PayConfigPath, Data.PayConfigDic);
            }

			return await Task.FromResult(BaseResultDto.Success());
		}

        /// <summary>
        /// 编辑支付配置
        /// </summary>
        [HttpPost("edit.pay.config")]
        public async Task<BaseResultDto> UpdatePayConfig(PayConfigAddDto model)
        {
            if (!Data.PayConfigDic.ContainsKey(model.PayCategory))
                return await Task.FromResult(BaseResultDto.Fail("支付类型对应配置不存在"));
            lock (_lockObj)
            {
                var data = Data.PayConfigDic[model.PayCategory];
				data.AppId = model.AppId;
				data.ServerIp = model.ServerIp;
				data.WechatPayVersion = model.WechatPayVersion;
				data.PayCategory = model.PayCategory;
				if (data.AlipayOption != null)
					data.AlipayOption.AppId = null;
				if (data.WeChatPayOption != null)
					data.WeChatPayOption.AppId = null;
				DeleteFile(data, model);
                data.WeChatPayOption = model.WeChatPayOption;
                data.AlipayOption = model.AlipayOption;
                ToolHelper.SaveJsonToFile(ToolHelper.PayConfigPath, Data.PayConfigDic);
            }

            return await Task.FromResult(BaseResultDto.Success());
        }

        /// <summary>
        /// 删除支付配置
        /// </summary>
        [HttpPost("delete.pay.config/{payCategory}")]
        public async Task<BaseResultDto> DeletePayConfig([Required, EnumDataType(typeof(PayCategoryEnum))]PayCategoryEnum payCategory)
        {
            if (Data.PayConfigDic.ContainsKey(payCategory))
			{
                lock (_lockObj)
                {
					var data = Data.PayConfigDic[payCategory];
                    Data.PayConfigDic.Remove(payCategory);
					DeleteFile(data, null);
                    ToolHelper.SaveJsonToFile(ToolHelper.PayConfigPath, Data.PayConfigDic);
                }
            }

            return await Task.FromResult(BaseResultDto.Success());
        }

		/// <summary>
		/// 获取文件内容
		/// </summary>
		[HttpPost("get.content/{filename}")]
		public async Task<LayuiResultDto<string>> GetContent(string filename)
		{
			var result = new LayuiResultDto<string>();
			result.Data = ToolHelper.GetContent(filename).Replace("\r\n","<br/>").Replace(" ", "&nbsp;");
			return await Task.FromResult(result);
		}

        /// <summary>
        /// 上传文件,返回物理路径
        /// </summary>
        [HttpPost("upload")]
        public async Task<LayuiResultDto<string>> UploadAsync([Required] IFormCollection files)
        {
			var result = new LayuiResultDto<string>();
			if (files.Files.Count == 0 || files.Files.Count > 1)
			{
				result.Code = 10000;
				result.Msg = "文件为空或数量过1";
				return result;
			}

			var file = files.Files[0];
            var suffix = DateTime.Now.ToString("yyyyMMddHHmmss");
			var dir = Directory.CreateDirectory(Path.Combine(AppContext.BaseDirectory, "DataConfig", "Cert"));
			var filename = files.Files[0].FileName;
			var tempIndex = filename.LastIndexOf('.');
			if (tempIndex == -1)
				filename = $"{filename}{suffix}";
			else
				filename = $"{filename[..tempIndex]}{suffix}{filename[tempIndex..]}";
			var filepath = Path.Combine(dir.FullName, filename);
			try
			{
				using FileStream fs = new FileStream(filepath, FileMode.Create);
				await file.CopyToAsync(fs);
			}
			catch(Exception e)
			{
				result.Code = 10000;
				result.Msg = $"文件保存失败|{e.Message}";
				return result;
			}

			result.Data = filepath;
			return result;
        }

		#region private methods
		/// <summary>
		/// 删除文件
		/// </summary>
		private void DeleteFile(PayConfigDto model, PayConfigAddDto request)
		{
			if (request == null)
			{
				DeleteFile(model.WeChatPayOption?.Certificate);
				DeleteFile(model.AlipayOption?.AlipayPublicCert);
				DeleteFile(model.AlipayOption?.AppPublicCert);
				DeleteFile(model.AlipayOption?.AlipayRootCert);
			}
			else
			{
				if (!string.IsNullOrWhiteSpace(model.WeChatPayOption?.Certificate) 
					&& request.WeChatPayOption?.Certificate != model.WeChatPayOption?.Certificate)
                    DeleteFile(model.WeChatPayOption?.Certificate);
                if (!string.IsNullOrWhiteSpace(model.AlipayOption?.AlipayPublicCert)
                    && request.AlipayOption?.AlipayPublicCert != model.AlipayOption?.AlipayPublicCert)
                    DeleteFile(model.AlipayOption?.AlipayPublicCert);
                if (!string.IsNullOrWhiteSpace(model.AlipayOption?.AppPublicCert)
                    && request.AlipayOption?.AppPublicCert != model.AlipayOption?.AppPublicCert)
                    DeleteFile(model.AlipayOption?.AppPublicCert);
                if (!string.IsNullOrWhiteSpace(model.AlipayOption?.AlipayRootCert)
                    && request.AlipayOption?.AlipayRootCert != model.AlipayOption?.AlipayRootCert)
                    DeleteFile(model.AlipayOption?.AlipayRootCert);
            }
		}

		/// <summary>
		/// 删除文件
		/// </summary>
		private void DeleteFile(string path)
		{
            try
            {
                if (System.IO.File.Exists(path))
				{
                    System.IO.File.Delete(path);
                }
            }
            catch { }
        }
        #endregion
    }
}